# Title     : TODO
# Objective : TODO
# Created by: yz
# Created on: 2018/3/1

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

library(optparse)
library(magrittr)
library(tidyverse)

option_list <- list(
  make_option("--d", type = 'character', action = "store", default = "./libs", help = "the database direcotry"),
  make_option("--base", default = "metabo_base.R", type = "character", help = "metabo base R file"),
  make_option("--config", default = "calculate_config.json", type = "character", help = "config file"),
  make_option("--pc", default = "", type = "character", help = "config file")

)
opt <- parse_args(OptionParser(option_list = option_list))

fileName <- "name_map.txt"

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))

if (!file.exists(fileName)) {
  quit(status = 0)
}

nameMapDf <- read_tsv(fileName)
ids <- nameMapDf$HMDB
if (all(is.na(ids))) {
  quit(status = 0)
}

diffData <- read_csv("AllMet_with_Anno.csv") %>%
  rowwise() %>%
  do({
    result <- as_tibble(.)
    id <- result[1, "KEGG"]
    metabolite <- result[1, "Metabolite"]
    ids <- str_split(id, "/") %>% unlist()
    metabolites <- str_split(metabolite, "/") %>% unlist()
    ids %>%
      map2_dfr(metabolites, function(id, metabolite) {
        result %>%
          mutate(KEGG = id, Metabolite = metabolite)
      })
  }) %>%
  ungroup()

diffData

configJson <- fromJSON(opt$config)
libType <- configJson$libType

load("idMapping_mSet.RData")

mSet <- SetMetabolomeFilter(mSet, F)

parent <- "./"
createWhenNoExist(parent)
msetList <- SetCurrentMsetLib(mSet, libType, 2, dataDir = opt$d)
inMset <- msetList$mSet
current.msetlib <- msetList$cMsetlib
fileName <- str_c(parent, "/MSEA_Result.csv")
inMset <- CalculateHyperScore(inMset, dataDir = opt$d, fileName = fileName, diffData = diffData)
save(inMset, current.msetlib, file = "enrich_mSet.RData")

